import {App} from 'vue'
import RouteKey from '@/constant/common-key'
import StorageKey from '@/constant/storage-key'
import {getDynamicRoute} from '@/util/authorize'
import {createRouter, createWebHashHistory, type Router} from 'vue-router'

// 路由不重定向白名单
const whiteList: Array<string> = [
    RouteKey.PAGE_PATH_404,
    RouteKey.PAGE_PATH_LOGIN,
    RouteKey.PAGE_PATH_LOGOUT,
    RouteKey.PAGE_PATH_REGISTER
]

const staticRoute = [
    {
        name: 'login',
        path: '/login',
        component: () => import('@/view/login.vue'),
        meta: {title: '登录'}
    },
    {
        name: '404',
        path: '/404',
        component: () => import('@/view/404.vue'),
        meta: {title: '404'}
    }
]

const layoutRoute = {
    path: '/',
    name: 'index',
    redirect: '/home',
    meta: {title: 'index'},
    component: () => import('@/layout/index.vue'),
    children: [
        {
            name: 'home',
            path: '/home',
            component: () => import('@/view/system/home/index.vue'),
            meta: {title: '首页'}
        }
    ]
}

const router: Router = createRouter({
    routes: [...staticRoute, layoutRoute],
    history: createWebHashHistory()
})

router.beforeEach(async (to, from, next) => {
    // 公共页面, 任何时候都可以跳转
    if (whiteList.includes(to.path)) {
        next()
        return
    }

    // 验证登录
    if (!localStorage.getItem(StorageKey.USER_TOKEN)) {
        next({path: '/login'})
        return
    }

    next()
})

router.afterEach((to) => {
    document.title = (to?.meta?.title as string) || 'index'
})

export async function setupRouter(app: App<Element>) {
    await getDynamicRoute()
    app.use(router)
}

export {router}
export default router
